<template>
  <div class="main-container">
    <div class="left_container">
      <div class="search_container">
        <div class="search_item">
          <div class="name">合同单号</div>
          <div class="input"><el-input v-model="pageData.code" clearable @clear="getList" /></div>
        </div>
        <div class="search_item">
          <div class="name">客户名称</div>
          <div class="input"><el-input v-model="pageData.customerName" clearable @clear="getList" /></div>
        </div>
        <div class="search_item">
          <div class="name" />
          <div class="input"><el-button type="search" @click.stop="getList">搜索</el-button></div>
        </div>
        <div class="search_item">
          <div class="name">签订日期</div>
          <div class="input">
            <TimeRangeSearch :band-value.sync="pageData.creatTime" @clearData="getList" />
          </div>
        </div>

        <div class="search_item">
          <div class="name">签订人员</div>
          <div class="input">
            <el-select v-model="pageData.signByName" filterable clearable>
              <el-option
                v-for="item in userOptions"
                :key="item.userId"
                :label="item.signBy"
                :value="item.realName"
              />
            </el-select>
          </div>
        </div>

        <div class="search_item">
          <div class="name">合同状态</div>
          <DictSelect :band-value.sync="pageData.statusDictCode" dict-type="contractState" />
        </div>
      </div>
      <div ref="middle_container" class="middle_container">
        <el-table
          ref="table"
          :data="tableData"
          stripe
          border
          :height="tableHeight"
          style="width: 99.9%"
          highlight-current-row
          @row-click="rowClick"
        >
          <el-table-column
            type="selection"
            width="50"
          />
          <el-table-column
            prop="code"
            label="合同单号"
            min-width="130"
          />
          <el-table-column
            prop="name"
            label="合同名称"
            min-width="150"
          />
          <el-table-column
            prop="customerName"
            label="客户名称"
            min-width="150"
          />
          <el-table-column
            prop="channelName"
            label="渠道名称"
            min-width="150"
          />
          <el-table-column
            prop="signDate"
            label="签订日期"
            min-width="120"
          />
          <el-table-column
            prop="endDate"
            label="到期日期"
            min-width="120"
          />
          <el-table-column
            prop="statusDictValue"
            label="合同状态"
          />
          <el-table-column
            prop="typeDictValue"
            label="合同类型"
          />
          <el-table-column
            prop="signByName"
            label="签订人员"
          />
          <el-table-column
            prop="payTypeDictValue"
            label="付款方式"
          />
          <el-table-column
            prop="totalMoney"
            label="合同总金额"
            min-width="120"
          />

          <infinite-loading
            ref="infiniteLoading"
            slot="append"
            force-use-infinite-wrapper=".el-table__body-wrapper"
            @infinite="loadNext"
          />
        </el-table>
      </div>
      <div class="button_container">
        <el-button type="add" @click.stop="add">新增</el-button>
        <RemoveButton :page="this" />
      </div>
    </div>
    <div class="right_container">
      <div class="header_container">
        编辑合同
      </div>
      <div class="add_container">
        <div class="add_item first">
          <div class="name"><label class="bitian">*</label>合同单号</div>
          <div v-if="isEdit" class="input">
            <RuleCodeDiv :band-value.sync="addData.code" table-name="sales_contract" column-name="code" />
          </div>
          <div v-else class="show">{{ addData.code }}</div>
        </div>
        <div class="add_item">
          <div class="name"><label class="bitian">*</label>合同名称</div>
          <div v-if="isEdit" class="input"><el-input v-model="addData.name" clearable placeholder="请填写" /></div>
          <div v-else class="show">{{ addData.name }}</div>
        </div>
        <div class="box">
          <div class="add_item first">
            <div class="name"><label class="bitian">*</label>客户名称</div>
            <div v-if="isEdit" class="input">
              <CustomerModelingSelect
                :band-value.sync="addData"
                show-prop="customerName"
              />
            </div>
            <div v-else class="show">{{ addData.customerName }}</div>
          </div>
        </div>
        <div class="add_item">
          <div class="name"><label class="bitian">*</label>签订日期</div>
          <div v-if="isEdit" class="input">
            <el-date-picker
              v-model="addData.signDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择"
              :editable="false"
            />
          </div>
          <div v-else class="show">{{ addData.signDate }}</div>
        </div>
        <div class="add_item">
          <div class="name">到期日期</div>
          <div v-if="isEdit" class="input">
            <el-date-picker
              v-model="addData.endDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择"
              :editable="false"
            />
          </div>
          <div v-else class="show">{{ addData.endDate }}</div>
        </div>
        <div class="add_item">
          <div class="name"><label class="bitian">*</label>合同状态</div>
          <div v-if="isEdit" class="input">
            <DictSelect :band-value.sync="addData.statusDictCode" dict-type="contractState" />
          </div>
          <div v-else class="show">{{ addData.statusDictValue }}</div>
        </div>
        <div class="add_item">
          <div class="name">合同类型</div>
          <div v-if="isEdit" class="input">
            <DictSelect :band-value.sync="addData.typeDictCode" dict-type="contractType" />
          </div>
          <div v-else class="show">{{ addData.typeDictValue }}</div>
        </div>
        <div class="add_item">
          <div class="name"><label class="bitian">*</label>签订人员</div>
          <div v-if="isEdit" class="input">
            <el-select v-model="addData.signBy" filterable clearable>
              <el-option
                v-for="item in userOptions"
                :key="item.userId+''"
                :label="item.realName"
                :value="item.userId+''"
              />
            </el-select>
          </div>
          <div v-else class="show">{{ addData.signByName }}</div>
        </div>
        <div class="add_item">
          <div class="name">付款方式</div>
          <div v-if="isEdit" class="input">
            <DictSelect :band-value.sync="addData.payTypeDictCode" dict-type="paymentWay" />
          </div>
          <div v-else class="show">{{ addData.payTypeDictValue }}</div>
        </div>
        <div class="add_container_header">添加产品</div>
        <div ref="table_container2" class="table_container dictDetail">
          <el-table
            ref="table2"
            :data="tableData2"
            stripe
            border
            :height="tableHeight2"
            style="width: 99.9%"
            :cell-class-name="cellClassName"
            :header-cell-class-name="headerCellClassName"
            :row-class-name="rowClassName"
          >
            <el-table-column
              prop="productCode"
              label="产品编码"
              min-width="100"
            >
              <template slot-scope="scope">
                <ProductSelect
                  v-if="!scope.row.isAdd&&isEdit"
                  :band-value.sync="scope.row"
                  delivery-method="2"
                  :row-index="scope.$index"
                  :set-data="setRowData"
                  show-prop="productCode"
                />

                <div v-else-if="!isEdit">{{ scope.row.productCode }}</div>
                <div v-else />
              </template>

            </el-table-column>
            <el-table-column
              prop="productName"
              label="产品名称"
              min-width="100"
            />
            <el-table-column
              prop="productTypeName"
              label="产品类型"
              min-width="100"
            />
            <el-table-column
              prop="productModel"
              label="产品规格"
              min-width="100"
            />
            <el-table-column
              prop="productMoney"
              label="销售价格"
              min-width="100"
            />
            <el-table-column
              prop="receivablePrice"
              label="应收价格"
              min-width="100"
            >
              <template slot-scope="scope">
                <el-input v-if="!scope.row.isAdd&&isEdit" v-model="scope.row.receivablePrice" @input="numChange(scope.$index)" />
                <div v-else-if="!isEdit">{{ scope.row.receivablePrice }}</div>
                <div v-else />
              </template>
            </el-table-column>
            <el-table-column
              prop="number"
              label="数量"
              min-width="100"
            >
              <template slot-scope="scope">
                <el-input v-if="!scope.row.isAdd&&isEdit" v-model="scope.row.number" @input="numChange(scope.$index)" />
                <div v-else-if="!isEdit">{{ scope.row.number }}</div>
                <div v-else />
              </template>
            </el-table-column>
            <el-table-column
              prop="sumPrice"
              label="总价"
              width="100"
            />
            <el-table-column
              v-if="isEdit"
              prop="operate"
              fixed="right"
              width="60"
            >
              <template slot-scope="scope">
                <el-button v-if="!scope.row.isAdd" class="el-icon-remove" style="font-size: 25px;color: #ff0000;height: 100%;width: 100%;border: 0px;background-color: transparent" @click.native="removeRow(scope.row)" />
                <el-button v-else class="el-icon-circle-plus" style="font-size: 25px;color: green;height: 100%;width: 100%;border: 0px;background-color: transparent" @click.native="addRow(scope.row)" />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="heji_container">
        <div class="name">合计</div>
        <div class="value3" />
        <div class="value2">{{ addData.totalAmount }}</div>
      </div>
      <div class="button_container">
        <el-button v-if="isEdit" type="save" @click.stop="save">保存</el-button>
        <el-button v-else type="edit" @click.stop="edit">编辑</el-button>
      </div>
    </div>

  </div>
</template>

<script>
import { list, add, remove, getInfo } from '@/api/sale/contractOrders'
import { list as getUser } from '@/api/system/user'
import { mapGetters } from 'vuex'
import Big from 'big.js' // big.js解决精度丢失问题
export default {
  name: 'Index',
  computed: {
    ...mapGetters([
      'userId', 'userName'
    ])
  },
  data() {
    return {
      pageData: {
        customerName: undefined,
        creatTime: undefined,
        signBy: undefined,
        statusDictCode: undefined,
        pageNum: 1,
        pageSize: 15,
        orderByColumn: 'updateTime',
        isAsc: 'desc'
      },
      addData: {
        id: '--',
        code: '--',
        name: '--',
        number: '--',
        customerId: '--',
        customerName: '--',
        signDate: '--',
        endDate: '--',
        channelName: '--',
        statusDictCode: '--',
        statusDictValue: '--',
        typeDictCode: '--',
        typeDictValue: '--',
        payTypeDictCode: '--',
        payTypeDictValue: '--',
        signByName: '--',
        signBy: '--',
        totalAmount: '--'
      },
      mainId: 'id',
      tableHeight: '0',
      tableData: [],
      tableHeight2: '300',
      tableData2: [],
      userOptions: [],
      triggerTag: false, // 触发标志，watch是否触发
      isEdit: false // false:右侧区域仅为展示,true:右侧区域可编辑
    }
  },
  watch: {
    'pageData.signDate'() {
      if (this.pageData.signDate == '' || this.pageData.signDate == undefined || this.pageData.signDate == null) {
        this.getList()
      }
    },
    'pageData.signByName'() {
      if (this.pageData.signByName == '' || this.pageData.signByName == undefined || this.pageData.signByName == null) {
        this.getList()
      }
    },
    'pageData.statusDictCode'() {
      if (this.pageData.statusDictCode == '' || this.pageData.statusDictCode == undefined || this.pageData.statusDictCode == null) {
        this.getList()
      }
    }
  },
  mounted() {
    this.getUser()
    this.$nextTick(() => {
      this.tableHeight = this.$refs.middle_container.offsetHeight
    })
  },
  methods: {
    headerCellClassName(data) {
      return ''
    },
    cellClassName(data) {
      if (data.column.property == 'operate' || data.column.property == 'sumPrice') {
        if (data.rowIndex % 2 == 0) { // 单数行
          return 'fixed one'
        } else { // 双数行
          return 'fixed two'
        }
      }
    },
    rowClassName({ row, rowIndex }) {
      if (rowIndex == this.tableData2.length - 1 && row.isAdd) {
        return 'addRow'
      }
    },
    rowClick(row, column, event) { // 单击行选中
      this.triggerTag = false
      this.getInfo(row)
      this.tableData2.splice(this.tableData2.indexOf(row), 1)
    },
    addRow() {
      // 如果最后一行是idAdd
      if (this.tableData2.length > 0 && this.tableData2[this.tableData2.length - 1].isAdd) {
        // 先删除最后一行
        this.tableData2.splice(this.tableData2.length - 1, 1)
      }

      // 再新增一行有输入框的
      // 最后补上一行空的
      const row2 = [
        {
          code: '',
          name: '',
          type: '',
          model: '',
          salePrice: '',
          receivablePrice: '',
          number: '',
          sumPrice: '',
          productId: ''
        },
        {
          isAdd: true
        }
      ]
      this.tableData2.push(...row2)
    },
    removeRow(row) {
      this.tableData2.splice(this.tableData2.indexOf(row), 1)
      this.countTotal()
    },
    getList() { // 获取数据
      this.pageData.pageNum = 1
      this.tableData = []
      this.$refs.infiniteLoading.$emit('$InfiniteLoading:reset')
    },
    loadNext($state) { // 加载下一页数据
      list(this.pageData).then(res => {
        if (res.data.length > 0) {
          this.tableData = this.tableData.concat(res.data)
          this.pageData.pageNum++
          $state.loaded()
        } else {
          $state.complete()
        }
      })
    },
    add() { // 新增按钮
      this.$refs.table.setCurrentRow(-1)// 清除高亮
      Object.keys(this.addData).forEach(key => { // 清空右边数据
        this.addData[key] = ''
      })
      this.tableData2 = []
      this.addRow()
      this.triggerTag = true
      this.isEdit = true // 右边输入框显示出来
    },
    edit() { // 编辑按钮
      if (this.addData[this.mainId] == '--') {
        this.$message({
          message: '请先选择要操作的数据',
          type: 'warning'
        })
      } else {
        this.tableData2.push({ isAdd: true })
        this.triggerTag = true
        this.isEdit = true // 右边输入框显示出来
      }
    },
    checkForm() {
      if (!this.addData.code) {
        this.$message({
          type: 'warning',
          message: '请输入合同单号'
        })
        return false
      }
      if (!this.addData.name) {
        this.$message({
          type: 'warning',
          message: '请输入合同名称'
        })
        return false
      }
      if (!this.addData.customerId) {
        this.$message({
          type: 'warning',
          message: '请选择客户名称'
        })
        return false
      }
      if (!this.addData.signDate) {
        this.$message({
          message: '请选择签订日期',
          type: 'warning'
        })
        return false
      }
      if (!this.addData.signBy) {
        this.$message({
          message: '请选择签订人员',
          type: 'warning'
        })
        return false
      }
      if (!this.addData.statusDictCode) {
        this.$message({
          message: '请选择合同状态',
          type: 'warning'
        })
        return false
      }
      let canDo = true
      const cacheTableData = (JSON.parse(JSON.stringify(this.tableData2)))
      if ((cacheTableData[cacheTableData.length - 1]).isAdd == true) {
        cacheTableData.splice(cacheTableData.length - 1, 1)
      }
      if (cacheTableData.length == 0) {
        this.$message({
          message: '请添加产品',
          type: 'warning'
        })
        canDo = false
      } else {
        cacheTableData.forEach(item => {
          if (canDo && !item.productCode) {
            this.$message({
              message: '请选择产品编码',
              type: 'warning'
            })
            canDo = false
          }
          if (canDo && !item.receivablePrice) {
            this.$message({
              message: '请输入应收价格',
              type: 'warning'
            })
            canDo = false
          }
          if (canDo && !item.number) {
            this.$message({
              message: '请输入数量',
              type: 'warning'
            })
            canDo = false
          }
        })
      }
      if (canDo) {
        return true
      } else {
        return false
      }
    },
    save() { // 保存按钮
      if (this.checkForm()) {
        const cacheData = (JSON.parse(JSON.stringify(this.addData)))
        const cacheTableData = (JSON.parse(JSON.stringify(this.tableData2)))
        if ((cacheTableData[cacheTableData.length - 1]).isAdd == true) {
          cacheTableData.splice(cacheTableData.length - 1, 1)
        }
        cacheData.data = cacheTableData
        cacheData.totalMoney = cacheData.totalAmount
        add(cacheData).then(res => {
          this.$message({
            message: res.msg,
            type: 'success'
          })
          this.getList()
          if (!this.addData[this.mainId]) { // 新增
            Object.keys(this.addData).forEach(key => { // 清空右边数据
              this.addData[key] = ''
            })
            this.tableData2 = []
            this.addRow()
          } else { // 编辑
            this.getInfo(cacheData)
          }
        })
      }
    },
    numChange(index) { // 计算行里的总价
      const reg = /(^[1-9](\d+)?(\.\d{1,3})?$)|(^\d\.\d{1,3}$)/
      const reg2 = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/
      const row = this.tableData2[index]
      if (row.receivablePrice && row.number && reg.test(row.number) && reg2.test(row.receivablePrice)) {
        row.sumPrice = new Big(row.number).times(row.receivablePrice).toString()
      } else {
        row.sumPrice = 0
      }
      this.countTotal()
    },
    countTotal() { // 计算总数和总价
      let sumPrice = 0
      this.tableData2.forEach(item => {
        if (item.sumPrice) {
          sumPrice = new Big(item.sumPrice).plus(sumPrice).toString()
        }
      })
      this.$set(this.addData, 'totalAmount', sumPrice)
    },
    setRowData(row, index) {
      this.$set(this.tableData2, index, row)
    },
    // 当前页的删除接口
    doRemove(data) {
      Object.keys(this.addData).forEach(key => { // 给右边数据赋值
        this.addData[key] = '--'
      })
      Object.keys(this.tableData2).forEach(key => { // 给右边数据赋值
        this.tableData2 = []
      })
      this.isEdit = false // 右边输入框隐藏
      return remove(data)
    },
    getInfo(row) { // 获取右侧数据
      getInfo(row[this.mainId]).then(res => {
        Object.keys(this.addData).forEach(key => { // 给右边数据赋值
          this.addData[key] = res.data[key] || ''
        })
        this.tableData2 = res.data.data

        this.countTotal()
      })
      this.isEdit = false // 右边输入框隐藏
    },
    getUser() { // 获取右侧数据
      getUser().then(res => {
        this.userOptions = res.data
      })
    }
  }
}
</script>

<style lang="less" scoped>
.main-container{
  .left_container{
    width: 60%;
    .search_container{
      .search_item{
        .name{
          width: 100px;
        }
      }
    }
  }
  .right_container{
    .add_container{
      .box{
        margin-top: 9px;
      }
      .add_item{
        .name{
          width: 88px;
        }
      }
    }
  }
  .heji_container{
    width: 100%;
    height: 50px;
    .name{
      float: left;
      width: 200px;
      height: 50px;
      display: flex;justify-content: center;align-items: center;
    }
    .value1{
      float: right;
      width: 100px;
      height: 50px;
      display: flex;justify-content: center;align-items: center;
    }
    .value2{
      float: right;
      width: 100px;
      height: 50px;
      display: flex;justify-content: center;align-items: center;
    }
    .value3{
      float: right;
      width: 100px;
      height: 50px;
      display: flex;justify-content: center;align-items: center;
    }
  }
}
</style>
